package com.cjh.admin.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cjh.admin.config.shiro.JwtToken;
import com.cjh.admin.utils.JwtUtil;
import com.cjh.common.dto.UserRoleDTO;
import com.cjh.common.entity.User;
import com.cjh.common.response.Result;
import com.cjh.common.service.PermissionService;
import com.cjh.common.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cjh
 * @since 2021-11-15
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    PermissionService permissionService;
    @PostMapping("/login")
    @ApiOperation("登录")
    public String login(@RequestBody User user){
        
        if (user.getUsername() == null || user.getPassword() == null) {
            return JSON.toJSONString(new Result().setCode(500).setMessage("账号密码不能为空"));
        }
        Subject subject = SecurityUtils.getSubject();
        String jwt = JwtUtil.createJWT(user.getUsername(),"back","user",1000 * 60 * 60 * 24 * 7);
        JwtToken jwtToken = new JwtToken(jwt, user.getPassword());

        try {
            subject.login(jwtToken);
        }catch (UnknownAccountException e){
            return JSON.toJSONString(new Result().setCode(401).setMessage("账号不存在！"));
        }catch (IncorrectCredentialsException e){
            return JSON.toJSONString(new Result().setCode(401).setMessage("密码错误！"));
        }
        User userByUsername = userService.getUserByUserName(user.getUsername());
        userByUsername.setPassword(null);
        userByUsername.setSalt(null);
        Map<String,Object> map = new HashMap<>();
        map.put("user",userByUsername);
        map.put("token", jwt);
        return JSON.toJSONString(new Result().setCode(200).setMessage("登录成功").setData(map));
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return new Result().setCode(200).setMessage("成功退出");
    }
    @ApiOperation("通过用户名搜索用户")
    @GetMapping("/getUserByLikeUsername")
    public Result getUserByListUsername(@RequestParam long current,@RequestParam long size,@RequestParam String username) {
        return userService.getUserByLikeUsername(new Page<>(current,size),username);
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getUserById")
    public Result getUserById(@RequestParam Integer id) {
        UserRoleDTO userById = userService.getUserById(id);
        return new Result().setCode(200).setMessage("操作成功").setData(userById);
    }

    @RequiresPermissions(value = {"addUser"})
    @ApiOperation("添加用户")
    @PostMapping("/addUser")
    public Result addUser(@RequestBody UserRoleDTO userRoleDTO) {
        return userService.addUser(userRoleDTO);
    }

    @RequiresPermissions(value = {"updateUser"})
    @ApiOperation("修改用户信息")
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody UserRoleDTO userRoleDTO) {
        if(permissionService.isSuperAdministrator(userRoleDTO.getUsername())){
            return new Result().setCode(201).setMessage("超级管理员无法修改！");
        }
        return userService.updateUser(userRoleDTO);
    }

    @RequiresPermissions(value = {"updateUser"})
    @ApiOperation("修改用户密码")
    @PostMapping("/updateUserPassword")
    public Result updateUserPassword(@RequestBody Map<String,String> map) {
        return userService.updateUserPassword(Integer.valueOf(map.get("id")), map.get("password") );
    }

    @RequiresPermissions(value = {"deleteUser"})
    @ApiOperation("删除用户")
    @PostMapping("/deleteUserById")
    public Result deleteUserById(@RequestBody Map<String,Integer> map) {
        return userService.deleteUserById(map.get("id"));
    }

    @RequiresPermissions(value = {"deleteUser"})
    @ApiOperation("删除多个用户")
    @PostMapping("/deleteUserByIdList")
    public Result deleteUserByIdList(@RequestBody List<Integer> list) {
        return userService.deleteUserByIdList(list);
    }
}
